# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 12:49:24 2019

@author: ikaros

生成单个汉字、字母的图片
"""

import random
from PIL import Image,ImageDraw,ImageFont
import os
import numpy as np
import cv2

 #验证码文字

def creat_chinese(width,height,rotate_flag,save_dir):
    '''
    width: 验证码图像宽度     #width = 50
    height:验证码高           #height = 50
    rotate_flag:True时对图片进行旋转，但是旋转后图片空缺地方会用黑色补上，需要进一步处理
    save_dir:图片保存地址
    '''
    data = ['数','学','口','算','题','卡','合','混','两','位','退','不','十','减','得',
            '分','对','错','时','间','一','二','成','绩','签','字','姓','名','年','级',
            '我','三','四','乘','法','的','青','春','年','好','坏','那','些','下','上',
            '版','班','学','校','除','分','钟','每','天','练','习','以','内','整','加',
            '连','续','进','幼','小','衔','接','术','主','编','作','者','道','出','社',
            '计','高','手','日','心','口','册','人','教','新','课','标','完','成','星',
            '期','做','该','改','正','栏','目','速','巧','笔','真','油','家','长','评',
            '价','第']
    
    mode = 'RGB'
    size = (width, height)
    color1 = "rgb(255,255,255)"
    
    word_num0 = 0
    for x in data:
        if not rotate_flag:            
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font='./Word style/msyh.ttf', size=60)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            #draw.text((0, -10), x, font=font, fill=(random.randint(0,100),random.randint(0,100),random.randint(0,100)))
            draw.text((0, -10), x, font=font, fill=(255,0,0))
        
        if rotate_flag:
            color1 = "rgb(0,0,0)"
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font='./Word style/msyh.ttf', size=40)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            draw.text((0, -10), x, font=font, fill=(255,255,255))
#            img = img.rotate(45,Image.BILINEAR, expand=255)
            img = img.rotate(random.randint(-170,180))
        while(True):
            name2 = save_dir + 'Cword'+'(' + str(word_num0) +')' + '.jpg'
            if os.path.exists(name2):
                word_num0 = word_num0 + 1
            else:           
                with open(name2,"wb") as f:
                    img.save(f,format="png")
                break
    return img

def creat_alphabet(width,height,rotate_flag,save_dir):
    font1 = 'simsun.ttc'
    alphabet1 = []
    for i in range(65,91):
        alphabet1.append(chr(i))
    for i in range(97,123):
        alphabet1.append(chr(i))
    mode = 'RGB'
    size = (width, height)
    color1 = "rgb(255,255,255)"
    
    Aword_num0 = 0
    for x in alphabet1:
        if not rotate_flag:            
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font=font1, size=31)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            draw.text((2, -3), x, font=font, fill=(random.randint(0,100),random.randint(0,100),random.randint(0,100)))
        
        if rotate_flag:
            color1 = "rgb(0,0,0)"
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font=font1, size=31)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            draw.text((0, -10), x, font=font, fill=(255,255,255))
#            img = img.rotate(45,Image.BILINEAR, expand=255)
            img = img.rotate(random.randint(-170,180),Image.BILINEAR,expand=1)
        while(True):
            name2 = save_dir + 'Aword'+'(' + str(Aword_num0) +')' + '.png'
            if os.path.exists(name2):
                Aword_num0 = Aword_num0 + 1
            else:           
                with open(name2,"wb") as f:
                    img.save(f,format="png")
                break
    
def creat_biaohao(width,height,rotate_flag,font_dir,save_dir):
    '''
    font_dir = 'Word style/Endylau.ttf'
    ---------------------------------------
    Endylau.ttf的数字对应的字符
    左边是键盘上的字符，右边是对应的数字，该字体包里没有0~10这几个数字。
    
    ！:11  @ :12  # :13  $ :14  % :15  ^:16  &:17  *:18  (:19  
    ):20  _:21  +:22  1:23  2:24  3:25  4:26  5:27  6:28  7:29  
    8:30  9:31  0:32  -:33  =:34  Q:35  W:36  E:37  R:38  T:39  
    Y:40  U:41  I:42  O :43  P:44  {:45  }:46  q:47  w:48  e:49
    r:50  t:51  y:52  u:53  i:54  o:55  p:56  [:57  ]:58  A:59    
    S:60  D:61  F:62  G:63  H:64  J:65  K:66  L:67  ::68  |:69
    a:70  s:71  d:72  f:73  g:74  h:75  j:76  k:77  l:78  ; : 79   
    ~ : 80  Z:81  X:82  C:83  V:84  B:85  N:86  :M87  <:88  >:89  
    ?:90  z:91  x:92  c:93  v:94  b:95  n:96  m:97  , :98  . :99  /:100
    '''
    biaohaos = []
    for i in range(58,92):
        biaohaos.append(chr(i))
    for i in range(10):
        biaohaos.append(str(i))
    for i in range(97,127):
        biaohaos.append(chr(i))
    for i in range(35,39):
        biaohaos.append(chr(i))
    for i in range(40,48):
        biaohaos.append(chr(i))
    for i in range(93,96):
        biaohaos.append(chr(i))
    biaohaos.append('!')
    mode = 'RGB'
    size = (width, height)
    color1 = "rgb(255,255,255)"
    
    biaohao_num0 = 0
    for x in biaohaos:
        if not rotate_flag:            
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font=font_dir, size=37)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            draw.text((2, 2), x, font=font, fill=(random.randint(0,100),random.randint(0,100),random.randint(0,100)))
        
        if rotate_flag:
            color1 = "rgb(0,0,0)"
            img = Image.new(mode, size, color1)  # 生成画布
            font = ImageFont.truetype(font=font_dir, size=31)  # 设置字体
            draw = ImageDraw.Draw(img)  # 创建画笔
            draw.text((0, 2), x, font=font, fill=(255,255,255))
#            img = img.rotate(45,Image.BILINEAR, expand=255)
            img = img.rotate(random.randint(-170,180),Image.BILINEAR)
        while(True):
            name2 = save_dir + 'biaohao'+'(' + str(biaohao_num0) +')' + '.png'
            if os.path.exists(name2):
                biaohao_num0 = biaohao_num0 + 1
            else:           
                with open(name2,"wb") as f:
                    img.save(f,format="png")
                break
    
def change_word_color(img_dir):
    '''
    img_dir:需要处理的图片的地址 [图片时黑底白字的]
    ---------------------------------------------------------------------------
    creat_chinese()中的rotate_flag为True时使用该函数将图片黑色空缺变成白色，
    注意其他没有旋转的图片若放在同一目录下，会受到影响，要先把不需要处理的图片分开再使用
    '''
    img_list = os.listdir(save_dir)    
    for im in img_list:
        name = img_dir + im
        img = cv2.imread(name)
#        B1,G1,R1 = random.randint(100,240),random.randint(100,240),random.randint(80,240)
        B2,G2,R2 = random.randint(0,100),random.randint(0,100),random.randint(0,100)
        for i in range(img.shape[0]):
            for j in range(img.shape[1]):
                if (img[i,j,0] < 10) and (img[i,j,1] < 10) and (img[i,j,2] < 10):
                    img[i,j,0] = 255
                    img[i,j,1] = 255
                    img[i,j,2] = 255
                elif (img[i,j,0] > 150) and (img[i,j,1] >150) and (img[i,j,2] >150):
                    img[i,j,0] = B2
                    img[i,j,1] = G2
                    img[i,j,2] = R2
        cv2.imwrite(name,img)

    
if __name__ == '__main__':
    save_dir = './biaohao/'
    font_dir = 'Word style/Endylau.ttf'
    #creat_biaohao(40,40,False,font_dir,save_dir)
    #creat_alphabet(20,30,False,save_dir)
    creat_chinese(60,60,False,save_dir)
    #change_word_color(save_dir)













